//
//  QHCommonTool.m
//  QHealthForDoctor
//
//  Created by 李志良 on 16/9/7.
//  Copyright © 2016年 李 志良. All rights reserved.
//

#import "QHCommonTool.h"
#import "AFNetworking.h"
#import "GTMBase64.h"

//#import "AFHTTPRequestOperationManager.h"
//#import "FMDatabase.h"

#import <sys/utsname.h>

static NSString *base64_encode_data(NSData *data){
    data = [data base64EncodedDataWithOptions:0];
    NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return ret;
}

@implementation QHCommonTool

+(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        return nil;
    }
    return dic;
}

+(NSString*)dictionaryTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

+(NSString *)dictionaryToxwwwFormUrlencoded:(id)object{
//    NSString *xwwwString = @"";
//    if ([object isKindOfClass:[NSDictionary class]]) {
//        NSDictionary *dict = (NSDictionary *)object;
//        NSArray *tempKeys = [dict allKeys];
//        NSArray *sortedKeys = [tempKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
//            return [obj1 compare:obj2];
//        }];
//        for (NSString *key in sortedKeys) {
//            xwwwString = [xwwwString stringByAppendingFormat:@"%@=%@&",key,[dict objectForKey:key]];
//        }
//        xwwwString = [xwwwString substringAtRange:NSMakeRange(0, xwwwString.length-1)];
//    }
//    NSString *tempStr = [xwwwString stringByReplacingOccurrencesOfString:@" " withString:@"+"];
//    NSString *encodeStr = [tempStr stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}[]|\"<> :"] invertedSet]];
    
    // @"!*'();:@&=+$,/?%#[]"
    //@"`#%^{}[]|\"<> :"
    
    return @"";//encodeStr;
}

+(NSString *)returnJsonstringwithObject:(id)aObject{
    NSString *jsonStr = @"";
    if ([aObject isKindOfClass:[NSDictionary class]]) {
        NSString *  jsonStr = [@"" stringByAppendingString:@"{"];
        NSDictionary *tempDic = (NSDictionary *)aObject;
        NSArray *tempKeys = [tempDic allKeys];
        NSArray *keys = [tempKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [obj1 compare:obj2];
        }];
        if (keys.count > 0) {
            for (NSString *key in keys) {
                jsonStr = [jsonStr stringByAppendingFormat:@"\"%@\":%@,",key,[self returnJsonstringwithObject:[tempDic objectForKey:key]]];
            }
            jsonStr = [jsonStr substringWithRange:NSMakeRange(0, jsonStr.length-1)];
        }
         jsonStr =[jsonStr stringByAppendingString:@"}"];
        return jsonStr;
    }else if ([aObject isKindOfClass:[NSArray class]]){
        jsonStr =[jsonStr stringByAppendingString:@"["];
        NSArray *tempArr = (NSArray *)aObject;
        if (tempArr.count > 0) {
            for (id object in tempArr) {
                jsonStr = [jsonStr stringByAppendingFormat:@"%@,",[self returnJsonstringwithObject:object]];
            }
            jsonStr = [jsonStr substringWithRange:NSMakeRange(0, jsonStr.length-1)];
        }
        jsonStr= [jsonStr stringByAppendingString:@"]"];
        return jsonStr;
    }else if ([aObject isKindOfClass:[NSNull class]]){
        jsonStr = [jsonStr stringByAppendingFormat:@"%@",@"null"];
        return  jsonStr;
    }else{
        jsonStr = [jsonStr stringByAppendingFormat:@"\"%@\"",aObject];
        return  jsonStr;
    }
    return jsonStr;
}

+(NSString*)dictionaryTOjsonStringOrdered:(id)object
{
    NSDictionary * tempDic = object;
    
    NSArray * keysArray = [tempDic allKeys];
    //对数组进行排序
    
    NSArray *result = [keysArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2]; //升序
    }];
    
    NSMutableString *mutableString = [NSMutableString string];
    [mutableString appendString:@"{"];
    if (result.count > 0) {
        for (NSInteger i = 0; i < result.count; i++) {
            if (i == result.count-1) {
                [mutableString appendFormat:@"\"%@\":\"%@\"", result[i], [tempDic objectForKey:result[i]]];
            } else {
                [mutableString appendFormat:@"\"%@\":\"%@\",", result[i], [tempDic objectForKey:result[i]]];
            }
        }
    }
    
    [mutableString appendString:@"}"];
    return mutableString;
}

+(float)caculateTheFormRowHeightWithLabelString:(NSString*)LabelString LabelTextFontSize:(float)TextFontSize LabelWidth:(float)LabelWidth{
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:TextFontSize], NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    CGSize detailsLabelSize = [LabelString boundingRectWithSize:CGSizeMake(LabelWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    return detailsLabelSize.height;
}

+(void)upLoadFileWithURL:(NSString*)aURL ParamDic:(NSDictionary*)paramDic Image:(UIImage*)aImage{
    //1-文件上传
    
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json",nil];
//    //设置请求类型
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    //设置响应类型
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    //设置请求类型 JSON
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    //KUrl_UFileUpload
//
//    AFHTTPRequestOperation *operation =
//    [manager POST:aURL parameters:paramDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
//
//        NSData * eachImgData = UIImageJPEGRepresentation(aImage, 0.5);
//        [formData appendPartWithFileData:eachImgData name:@"file" fileName:[NSString stringWithFormat:@"img.jpg"] mimeType:@"image/jpeg"];
//
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        //成功后回调
//        NSLog(@"%@",responseObject);
//
//        NSDictionary *str = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"%@",str);
//
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//
//    }];
//
//    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
//        //进度
//        NSLog(@"%f",totalBytesWritten*1.0/totalBytesExpectedToWrite);
//        //  self.progressBlock(totalBytesWritten*1.0/totalBytesExpectedToWrite);
//    }];

}

+(void)upLoadFileWithURL2:(NSString*)aURL ParamDic:(NSDictionary*)paramDic Image:(UIImage*)aImage UploadSuccessBlock:(UploadFileSuccessBlock)block{
   
//    NSData * eachImgData = UIImageJPEGRepresentation(aImage, 0.5);
//    NSString * base64String = base64_encode_data(eachImgData);
//    NSMutableDictionary * mutDic = [[NSMutableDictionary alloc]initWithDictionary:paramDic];
//    [mutDic setObject:base64String forKey:@"Files"];
//    [[QHUserTokenManager sharedManager]getWebServiceToken:^(NSString *token) {//先验证token是否过期
//        [AFNHttpTools requestWithUrl:aURL andPostDict:mutDic andAuthToken:AUTH_TOKEN successed:^(NSDictionary *dict) {
//            if ([dict[@"errorcode"]compare:@"00000000"]==NSOrderedSame) {
//                if (block) {
//                    block(dict[@"data"]);
//                }
//            }
//        } failed:^(NSError *err) {
//
//        }];
//
//
//    }];

}

+(NSString *) utf8ToUnicode:(NSString *)string

{
    
    NSUInteger length = [string length];
    
    NSMutableString *s = [NSMutableString stringWithCapacity:0];
    
    for (int i = 0;i < length; i++)
        
    {
        
        unichar _char = [string characterAtIndex:i];
        
        //判断是否为英文和数字
        
        if (_char <= '9' && _char >= '0')
            
        {
            
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
            
        }
        
        else if(_char >= 'a' && _char <= 'z')
            
        {
            
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
            
            
            
        }
        
        else if(_char >= 'A' && _char <= 'Z')
            
        {
            
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
            
            
            
        }
        
        else
            
        {
            
            [s appendFormat:@"\\u%x",[string characterAtIndex:i]];
            
        }
        
    }
    
    return s;
    
}

+ (NSString*) replaceUnicode:(NSString*)aUnicodeString

{
    
    NSString *tempStr1 = [aUnicodeString stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                           
                                                           mutabilityOption:NSPropertyListImmutable
                           
                                                                     format:NULL
                           
                                                           errorDescription:NULL];
    
    
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
    
}

+(NSString*)reductionCIDWithDecodeCID:(NSString*)DecodeCID{
    NSMutableString * returnString = [[NSMutableString alloc]initWithString:DecodeCID];
    [returnString insertString:@"-" atIndex:8];
    [returnString insertString:@"-" atIndex:13];
    [returnString insertString:@"-" atIndex:18];
    [returnString insertString:@"-" atIndex:23];
    return returnString;
}


+(void)saveSomeData{
    //1.获得数据库文件的路径
    NSString *libs = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
    
    NSString *fileName = [libs stringByAppendingPathComponent:@"LocalDatabase"];
    
    NSError *err;
    if ([[NSFileManager defaultManager] fileExistsAtPath: fileName])
    {

    }
    else
    {
        if ([[NSFileManager defaultManager] createDirectoryAtPath: fileName withIntermediateDirectories:NO attributes: nil error:&err])
        {
            NSURL *nosyncURL = [NSURL fileURLWithPath: fileName];
            if (![nosyncURL setResourceValue: [NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &err])
            {

            }
        }
        else
        {

        }
    }

//    NSString *sqlFilePath = [fileName stringByAppendingPathComponent:@"__mydb"];

    
//    //2.获得数据库
//    FMDatabase *db = [FMDatabase databaseWithPath:sqlFilePath];
//
//    //3.使用如下语句，如果打开失败，可能是权限不足或者资源不足。通常打开完操作操作后，需要调用 close 方法来关闭数据库。在和数据库交互 之前，数据库必须是打开的。如果资源或权限不足无法打开或创建数据库，都会导致打开失败。
//    if ([db open])
//    {
//        //4.创表
//        BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS _ionickv (id integer PRIMARY KEY AUTOINCREMENT, key text NOT NULL, value text NOT NULL);"];
//        if (result)
//        {
//            NSLog(@"创建表成功");
//            NSString *oldVersion = kAppVersion;
//            [db executeUpdate:@"INSERT OR REPLACE INTO _ionickv (id, key, value) VALUES (?, ?, ?)",@"1001",@"emhlc2hpaXlnZW1peWFv",[NSString stringWithFormat:@"\"sWd3FmTa|G1eQdh@SD976RkYI|IOS|%@|%@\"",[QHCommonTool getDeviceID],oldVersion]];
//        }
//    }
//
//    [db close];
    
    [self saveMaviHeight];
}

+(void)saveMaviHeight{
    //1.获得数据库文件的路径
    NSString *libs = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
    
    NSString *fileName = [libs stringByAppendingPathComponent:@"LocalDatabase"];
    
    NSError *err;
    if ([[NSFileManager defaultManager] fileExistsAtPath: fileName])
    {
        
    }
    else
    {
        if ([[NSFileManager defaultManager] createDirectoryAtPath: fileName withIntermediateDirectories:NO attributes: nil error:&err])
        {
            NSURL *nosyncURL = [NSURL fileURLWithPath: fileName];
            if (![nosyncURL setResourceValue: [NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &err])
            {
                
            }
        }
        else
        {
            
        }
    }
//
//    NSString *sqlFilePath = [fileName stringByAppendingPathComponent:@"__mydb"];
//
//
//    //2.获得数据库
//    FMDatabase *db = [FMDatabase databaseWithPath:sqlFilePath];
//
//    //3.使用如下语句，如果打开失败，可能是权限不足或者资源不足。通常打开完操作操作后，需要调用 close 方法来关闭数据库。在和数据库交互 之前，数据库必须是打开的。如果资源或权限不足无法打开或创建数据库，都会导致打开失败。
//    if ([db open])
//    {
//        //4.创表
//        BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS _ionickv (id integer PRIMARY KEY AUTOINCREMENT, key text NOT NULL, value text NOT NULL);"];
//        if (result)
//        {
//            NSLog(@"创建表成功");
//            //获取状态栏的rect
//            CGRect statusRect = [[UIApplication sharedApplication] statusBarFrame];
//            //获取导航栏的rect
//            //那么导航栏+状态栏的高度
//            int save_height = statusRect.size.height;
//
//            [db executeUpdate:@"INSERT OR REPLACE INTO _ionickv (id, key, value) VALUES (?, ?, ?)",@"1003",@"NativeAppHeight",[NSString stringWithFormat:@"%d",save_height]];
//        }
//    }
//
//    [db close];
//
}


//+(void)saveUnreadNotificationEntity:(PushNotification_Entity*)notificationEntity{
//    //1.获得数据库文件的路径
//    NSString *libs = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
//    NSString *fileName = [libs stringByAppendingPathComponent:@"LocalDatabase"];
//    NSError *err;
//    if (![[NSFileManager defaultManager] fileExistsAtPath: fileName])
//    {
//        if ([[NSFileManager defaultManager] createDirectoryAtPath: fileName withIntermediateDirectories:NO attributes: nil error:&err])
//        {
//            NSURL *nosyncURL = [NSURL fileURLWithPath: fileName];
//            if (![nosyncURL setResourceValue: [NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &err])
//            {
//
//            }
//        }
//    }
//    
////    NSString *sqlFilePath = [fileName stringByAppendingPathComponent:@"__mydb"];
//    
////    //2.获得数据库
////    FMDatabase *db = [FMDatabase databaseWithPath:sqlFilePath];
////
////    NSDictionary * temDic = @{@"messageType":notificationEntity.type,@"messageRoute":notificationEntity.route};
////    NSMutableArray * tempArray = [NSMutableArray arrayWithArray:[self fetchUnReadNotifications]];
////    [tempArray addObject:temDic];
////    NSString * jsonString = [self dictionaryTOjsonString:tempArray];
////    //3.使用如下语句，如果打开失败，可能是权限不足或者资源不足。通常打开完操作操作后，需要调用 close 方法来关闭数据库。在和数据库交互 之前，数据库必须是打开的。如果资源或权限不足无法打开或创建数据库，都会导致打开失败。
////    if ([db open])
////    {
////        //4.创表
////        BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS _ionickv (id integer PRIMARY KEY AUTOINCREMENT, key text NOT NULL, value text NOT NULL);"];
////        if (result)
////        {
////            NSLog(@"创建表成功");
////            [db executeUpdate:@"INSERT OR REPLACE INTO _ionickv (id, key, value) VALUES (?, ?, ?)",@"1002",@"unreadMessageRoutes",jsonString];
////        }
////    }
////    [db close];
//}


+ (NSArray*)fetchUnReadNotifications{
    //1.获得数据库文件的路径
    NSString *libs = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
    
    NSString *fileName = [libs stringByAppendingPathComponent:@"LocalDatabase"];
    
    NSError *err;
    if (![[NSFileManager defaultManager] fileExistsAtPath: fileName])
    {
        if ([[NSFileManager defaultManager] createDirectoryAtPath: fileName withIntermediateDirectories:NO attributes: nil error:&err])
        {
            NSURL *nosyncURL = [NSURL fileURLWithPath: fileName];
            if (![nosyncURL setResourceValue: [NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &err])
            {
                
            }
        }
    }
    
//    NSString *sqlFilePath = [fileName stringByAppendingPathComponent:@"__mydb"];
    
//    //2.获得数据库
//    FMDatabase *db = [FMDatabase databaseWithPath:sqlFilePath];
//    BOOL res = [db open];
//    if (res == NO) {
//        NSLog(@"打开失败");
//        return nil;
//    }
//
//    FMResultSet* set = [db executeQuery:@"select * from _ionickv WHERE key='unreadMessageRoutes'"];//FMResultSet相当于游标集
//    //创建数组，保存消息
//    NSMutableArray* array = [NSMutableArray arrayWithCapacity:0];
//    //遍历unreadMessageRoutes表
//    while ([set next]) {//有下一个的话，就取出它的数据，然后关闭数据库
//        NSString* unReadMessages = [set stringForColumn:@"value"];
//        unReadMessages = [unReadMessages stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//        NSArray * tempArray = (NSArray*)[self dictionaryWithJsonString:unReadMessages];
//        if (tempArray.count!=0) {
//            [array addObjectsFromArray:tempArray];
//        }
//        break;
//    }
//
//    [db close];
    
    return [NSArray array];//array;
}

+(void)deleteUserInfo{
    //1.获得数据库文件的路径
//    NSString *libs = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
//
//    NSString *fileName = [libs stringByAppendingPathComponent:@"LocalDatabase"];
    
//    NSString *sqlFilePath = [fileName stringByAppendingPathComponent:@"__mydb"];
//
//    //2.获得数据库
//    FMDatabase *db = [FMDatabase databaseWithPath:sqlFilePath];
//
//    //3.使用如下语句，如果打开失败，可能是权限不足或者资源不足。通常打开完操作操作后，需要调用 close 方法来关闭数据库。在和数据库交互 之前，数据库必须是打开的。如果资源或权限不足无法打开或创建数据库，都会导致打开失败。
//    if ([db open])
//    {
////        [db executeUpdate:@"DELETE FROM _ionickv"];
////        [db executeUpdate:@"DELETE FROM _ionickv WHERE id = '1001'"];
//        [db executeUpdate:@"DELETE FROM _ionickv WHERE key = 'userInfo'"];
//    }
//
//    [db close];
}


+(NSString*)getDeviceID
{
    NSString *adId = [ASHYKeyChain getKeychain:USER_INFO_SERVER_NAME withTheKey:UUID_KEY];
    if (adId)
    {
        return adId;
    }else
    {
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        adId = (NSString *)CFBridgingRelease(CFUUIDCreateString (kCFAllocatorDefault,uuidRef));
        @autoreleasepool
        {
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
            [dic setObject:adId forKey:UUID_KEY];
            [ASHYKeyChain save:USER_INFO_SERVER_NAME data:dic];
        }
    }
    return adId;
}

+(NSString*)getPhoneType{
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString*platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if([platform isEqualToString:@"iPhone1,1"]){return @"iPhone2G";}
    
    if([platform isEqualToString:@"iPhone1,2"]) {return@"iPhone3G";}
    
    if([platform isEqualToString:@"iPhone2,1"])  {return@"iPhone3GS";}
    
    if([platform isEqualToString:@"iPhone3,1"]) {return@"iPhone4";}
    
    if([platform isEqualToString:@"iPhone3,2"]) {return@"iPhone4";}
    
    if([platform isEqualToString:@"iPhone3,3"]) {return@"iPhone4";}
    
    if([platform isEqualToString:@"iPhone4,1"]) {return@"iPhone4S";}
    
    if([platform isEqualToString:@"iPhone5,1"]) {return@"iPhone5";}
    
    if([platform isEqualToString:@"iPhone5,2"]) {return@"iPhone5";}
    
    if([platform isEqualToString:@"iPhone5,3"]) {return@"iPhone5c";}
    
    if([platform isEqualToString:@"iPhone5,4"]) {return@"iPhone5c";}
    
    if([platform isEqualToString:@"iPhone6,1"]) {return@"iPhone5s";}
    
    if([platform isEqualToString:@"iPhone6,2"]) {return@"iPhone5s";}
    
    if([platform isEqualToString:@"iPhone7,1"]) {return@"iPhone6Plus";}
    
    if([platform isEqualToString:@"iPhone7,2"]) {return@"iPhone6";}
    
    if([platform isEqualToString:@"iPhone8,1"]) {return@"iPhone6s";}
    
    if([platform isEqualToString:@"iPhone8,2"]) {return@"iPhone6sPlus";}
    
    if([platform isEqualToString:@"iPhone8,4"]) {return@"iPhoneSE";}
    
    if([platform isEqualToString:@"iPhone9,1"]) {return@"iPhone7";}
    
    if([platform isEqualToString:@"iPhone9,2"]) {return@"iPhone7Plus";}
    
    if([platform isEqualToString:@"iPhone10,1"]) {return@"iPhone8";}
    
    if([platform isEqualToString:@"iPhone10,4"]) {return@"iPhone8";}
    
    if([platform isEqualToString:@"iPhone10,2"]) return@"iPhone8Plus";
    
    if([platform isEqualToString:@"iPhone10,5"]) return@"iPhone8Plus";
    
    if([platform isEqualToString:@"iPhone10,3"]) return@"iPhoneX";
    
    if([platform isEqualToString:@"iPhone10,6"]) return@"iPhoneX";
    
    if([platform isEqualToString:@"iPod1,1"]) return@"iPodTouch1G";
    
    if([platform isEqualToString:@"iPod2,1"]) return@"iPodTouch2G";
    
    if([platform isEqualToString:@"iPod3,1"]) return@"iPodTouch3G";
    
    if([platform isEqualToString:@"iPod4,1"]) return@"iPodTouch4G";
    
    if([platform isEqualToString:@"iPod5,1"]) return@"iPodTouch5G";
    
    if([platform isEqualToString:@"iPad1,1"]) return@"iPad1G";
    
    if([platform isEqualToString:@"iPad2,1"]) return@"iPad2";
    
    if([platform isEqualToString:@"iPad2,2"]) return@"iPad2";
    
    if([platform isEqualToString:@"iPad2,3"]) return@"iPad2";
    
    if([platform isEqualToString:@"iPad2,4"]) return@"iPad2";
    
    if([platform isEqualToString:@"iPad2,5"]) return@"iPadMini1G";
    
    if([platform isEqualToString:@"iPad2,6"]) return@"iPadMini1G";
    
    if([platform isEqualToString:@"iPad2,7"]) return@"iPadMini1G";
    
    if([platform isEqualToString:@"iPad3,1"]) return@"iPad3";
    
    if([platform isEqualToString:@"iPad3,2"]) return@"iPad3";
    
    if([platform isEqualToString:@"iPad3,3"]) return@"iPad3";
    
    if([platform isEqualToString:@"iPad3,4"]) return@"iPad4";
    
    if([platform isEqualToString:@"iPad3,5"]) return@"iPad4";
    
    if([platform isEqualToString:@"iPad3,6"]) return@"iPad4";
    
    if([platform isEqualToString:@"iPad4,1"]) return@"iPadAir";
    
    if([platform isEqualToString:@"iPad4,2"]) return@"iPadAir";
    
    if([platform isEqualToString:@"iPad4,3"]) return@"iPadAir";
    
    if([platform isEqualToString:@"iPad4,4"]) return@"iPadMini2G";
    
    if([platform isEqualToString:@"iPad4,5"]) return@"iPadMini2G";
    
    if([platform isEqualToString:@"iPad4,6"]) return@"iPadMini2G";
    
    if([platform isEqualToString:@"iPad4,7"]) return@"iPadMini3";
    
    if([platform isEqualToString:@"iPad4,8"]) return@"iPadMini3";
    
    if([platform isEqualToString:@"iPad4,9"]) return@"iPadMini3";
    
    if([platform isEqualToString:@"iPad5,1"]) return@"iPadMini4";
    
    if([platform isEqualToString:@"iPad5,2"]) return@"iPadMini4";
    
    if([platform isEqualToString:@"iPad5,3"]) return@"iPadAir2";
    
    if([platform isEqualToString:@"iPad5,4"]) return@"iPadAir2";
    
    if([platform isEqualToString:@"iPad6,3"]) return@"iPadPro9.7";
    
    if([platform isEqualToString:@"iPad6,4"]) return@"iPadPro9.7";
    
    if([platform isEqualToString:@"iPad6,7"]) return@"iPadPro12.9";
    
    if([platform isEqualToString:@"iPad6,8"]) return@"iPadPro12.9";
    
    if([platform isEqualToString:@"i386"]) return@"iPhoneSimulator";
    
    if([platform isEqualToString:@"x86_64"]) return@"iPhoneSimulator";
    
    return platform;
}

+(NSString*)getSystemVersion{
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    return phoneVersion;
}

+ (UIViewController *)getPresentedViewController
{
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;

    }
    return topVC;
}

+(void)messageHasUnRead:(CheckHasUnReadMessageBlock)checkHasUnReadMessageBlock{
//    if (USER_LOGIN_MODEL.cid){
//        NSDictionary * paramDic = [NSDictionary dictionary];
//        paramDic = @{@"cid":USER_LOGIN_MODEL.cid};
//        [AFNHttpTools getDataNoTokenWithUrl:GET_HAS_UNREAD_MESSAGES_URL andParameters:paramDic successed:^(NSDictionary *dict) {
//            if (checkHasUnReadMessageBlock&& [dict[@"errorcode"] compare:@"00000000"]==NSOrderedSame) {
//                checkHasUnReadMessageBlock([dict[@"data"] boolValue]);
//            }
//        } failed:^(NSError *err) {
//
//        }];
//    }
}

+(void)saveEnterBackgroundTime{
//    [[NSUserDefaults standardUserDefaults]rm_setCustomObject:[TimeTool nowTimeStr2] forKey:ENTER_BACK_GROUND_TIME];
}

+(BOOL)isCrossTheMidNight{
//    NSString * nowTime = [TimeTool nowTimeStr2];
//    NSString * enterBackGroundTime = [[NSUserDefaults standardUserDefaults]rm_customObjectForKey:ENTER_BACK_GROUND_TIME];
//    if ([nowTime intValue]-[enterBackGroundTime intValue]!=0) {
//        return YES;
//    }else{
//        return NO;
//    }
    return YES;
}

+(NSURL *)videoConvertToMp4:(NSURL *)movUrl {
    NSURL *mp4Url = nil;
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        path = [path stringByAppendingPathComponent:@"EMDemoRecord"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        }
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetHighestQuality];
        NSString *mp4Path = [NSString stringWithFormat:@"%@/%d%d.mp4", path, (int)[[NSDate date] timeIntervalSince1970], arc4random() % 100000];
        mp4Url = [NSURL fileURLWithPath:mp4Path];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed: {
                    NSLog(@"failed, error:%@.", exportSession.error);
                } break;
                case AVAssetExportSessionStatusCancelled: {
                    NSLog(@"cancelled.");
                } break;
                case AVAssetExportSessionStatusCompleted: {
                    NSLog(@"completed.");
                } break;
                default: {
                    NSLog(@"others.");
                } break;
            }
            dispatch_semaphore_signal(wait);
        }];
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
            NSLog(@"timeout.");
        }
        
        if (wait) {
            //dispatch_release(wait);
            wait = nil;
        }
    }
    return mp4Url;
}

+(NSURL *)ConvertToMp4:(NSURL *)movUrl WithAsset:(AVAsset *)asset
{
    AVAsset *avAsset = asset;
    NSURL *mp4Url = nil;
    if (!asset) {
        avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    }
    
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetHighestQuality];
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        path = [path stringByAppendingPathComponent:@"EMDemoRecord"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSString *mp4Path = [NSString stringWithFormat:@"%@/%d%d.mp4",path, (int)[[NSDate date] timeIntervalSince1970], arc4random() % 100000];
        mp4Url = [NSURL fileURLWithPath:mp4Path];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(01);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed:
                    
                    break;
                 case AVAssetExportSessionStatusCancelled:
                    
                    break;
                case AVAssetExportSessionStatusCompleted:
                    break;
                    
                    
                default:
                    break;
            }
            dispatch_semaphore_signal(wait);
        }];
        
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
            
        }
        if (wait) {
            wait = nil;
        }
        
    }
    
    return mp4Url;
}

+(UserModel *)getUserInfoWithIDNumber:(NSString *)idNumber{
    NSString *brithDay = @"";
    if (idNumber.length < 18) {
        return nil;
    }
    //640381 19871120 2750
    brithDay = [idNumber substringWithRange:NSMakeRange(6, 8)];
    
    NSMutableString *mutableStr = [[NSMutableString alloc]initWithString:brithDay];
    [mutableStr insertString:@"." atIndex:4];
    [mutableStr insertString:@"." atIndex:7];
    UserModel *user = [[UserModel alloc]init];
    user.brithDay = [mutableStr copy];
    NSInteger gender = [[idNumber substringWithRange:NSMakeRange(idNumber.length-2, 1)]integerValue];
    if (gender %2 == 0) {
        user.gender = 2;
    }else{
        user.gender = 1;
    }
    NSTimeInterval timeStamp = [TimeTool getTimeStampByDate:brithDay];
    NSInteger age = fabs(timeStamp)/(60*60*24*365);
    NSString *ageStr = [NSString stringWithFormat:@"%ld",(long)age];
    user.age = ageStr;
    return user;
}

+(NSArray *)getCommonBanks
{
    return @[@"招商银行",@"广发银行",@"交通银行",@"中信银行",@"邮储银行",@"平安银行",@"天津银行",@"建设银行",@"中国银行",@"农业银行",@"工商银行"];
}

+(NSInteger)getRamdomNumberUnder:(NSInteger)max noNumber:(NSInteger)num
{
    NSInteger result = 0;
    result = arc4random()%max;
    if (result == num) {
     result = [self getRamdomNumberUnder:max noNumber:num];
    }
    return result;
}


@end
